/*
 * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.admin.bilibiliijkplayer.activities;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.example.admin.bilibiliijkplayer.R;
import com.example.admin.bilibiliijkplayer.application.AppActivity;
import com.example.admin.bilibiliijkplayer.application.Settings;
import com.example.admin.bilibiliijkplayer.eventbus.FileExplorerEvents;
import com.example.admin.bilibiliijkplayer.fragments.FileListFragment;
import com.example.admin.bilibiliijkplayer.interfaces.IAudioPlayer;
import com.example.admin.bilibiliijkplayer.services.AudioServiceController;
import com.squareup.otto.Subscribe;

import java.io.File;
import java.io.IOException;

import tv.danmaku.ijk.media.exo.IjkExoMediaPlayer;
import tv.danmaku.ijk.media.player.AndroidMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.TextureMediaPlayer;


public class FileExplorerActivity extends AppActivity implements IAudioPlayer {
    private Settings mSettings;
    IMediaPlayer mediaPlayer;
    AudioServiceController mAudioController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (mSettings == null) {
            mSettings = new Settings(this);
        }

        String lastDirectory = mSettings.getLastDirectory();
        if (!TextUtils.isEmpty(lastDirectory) && new File(lastDirectory).isDirectory())
            doOpenDirectory(lastDirectory, false);
        else
            doOpenDirectory("/", false);

        //-------------------------------------------------------
//        IjkMediaPlayer.loadLibrariesOnce(null);
//        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
//        Uri uri = Uri.parse("http://video.kocla.com/o_1ao0eu4l014d91935iqd1sng5q39.mp3?e=1476858694&token=kEUFey_36xJqHaOhr44fNd8eNUo4a9TLtMJSrqhu:xzavWVbcMoC0uNkCwPemXSHYcmg=");
//        mediaPlayer = createPlayer(uri, 1);
//        try {
//            mediaPlayer.setDataSource(uri.toString());
//            MediaPlayerService.intentToStart(this);
//            MediaPlayerService.setMediaPlayer(mediaPlayer);
//            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            mediaPlayer.setScreenOnWhilePlaying(true);
//            mediaPlayer.prepareAsync();
//            mediaPlayer.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
//                @Override
//                public void onPrepared(IMediaPlayer iMediaPlayer) {
//                    mediaPlayer.start();
//                }
//            });
//            mediaPlayer.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
//                @Override
//                public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
//                    return false;
//                }
//            });
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        //-------------------------------------------------------
//        String test = "http://video.kocla.com/kocla_f2497946ec384a29a2e821d63fcd4899.3GP?e=2139719453&token=kEUFey_36xJqHaOhr44fNd8eNUo4a9TLtMJSrqhu:KgOayXZ8RPd7t-hkOwEpgUzahtA=";
//        final List<String> lists = new ArrayList<>();
//        lists.add(test);
//        mAudioController = AudioServiceController.getInstance();
//        AudioServiceController.getInstance().bindAudioService(this);
//        AudioServiceController.getInstance().addAudioPlayer(this);
//        final View testView = new TextView(this);
//        testView.setId(1);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                AudioServiceController.getInstance().load(lists, 0, testView);
//            }
//        }, 1000);

    }

    @Override
    protected void onResume() {
        super.onResume();
        FileExplorerEvents.getBus().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        FileExplorerEvents.getBus().unregister(this);
        //mediaPlayer.stop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioServiceController.getInstance().unbindAudioService(this);
    }

    private void doOpenDirectory(String path, boolean addToBackStack) {
        Fragment newFragment = FileListFragment.newInstance(path);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        transaction.replace(R.id.body, newFragment);

        if (addToBackStack)
            transaction.addToBackStack(null);
        transaction.commit();
    }

    @Subscribe
    public void onClickFile(FileExplorerEvents.OnClickFile event) {
        File f = event.mFile;
        try {
            f = f.getAbsoluteFile();
            f = f.getCanonicalFile();
            if (TextUtils.isEmpty(f.toString()))
                f = new File("/");
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (f.isDirectory()) {
            String path = f.toString();
            mSettings.setLastDirectory(path);
            doOpenDirectory(path, true);
        } else if (f.exists()) {
            VideoActivity.intentTo(this, f.getPath(), f.getName());
        }
    }

    public IMediaPlayer createPlayer(Uri mUri, int playerType) {
        IMediaPlayer mediaPlayer = null;

        switch (playerType) {
            case Settings.PV_PLAYER__IjkExoMediaPlayer: {
                IjkExoMediaPlayer IjkExoMediaPlayer = new IjkExoMediaPlayer(this.getApplicationContext());
                mediaPlayer = IjkExoMediaPlayer;
            }
            break;
            case Settings.PV_PLAYER__AndroidMediaPlayer: {
                AndroidMediaPlayer androidMediaPlayer = new AndroidMediaPlayer();
                mediaPlayer = androidMediaPlayer;
            }
            break;
            case Settings.PV_PLAYER__IjkMediaPlayer:
            default: {
                IjkMediaPlayer ijkMediaPlayer = null;
                if (mUri != null) {
                    ijkMediaPlayer = new IjkMediaPlayer();
                    ijkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_DEBUG);
                    if (mSettings.getUsingMediaCodec()) {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
                        if (mSettings.getUsingMediaCodecAutoRotate()) {
                            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
                        } else {
                            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 0);
                        }
                        if (mSettings.getMediaCodecHandleResolutionChange()) {
                            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 1);
                        } else {
                            ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 0);
                        }
                    } else {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 0);
                    }

                    if (mSettings.getUsingOpenSLES()) {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 1);
                    } else {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 0);
                    }

                    String pixelFormat = mSettings.getPixelFormat();
                    if (TextUtils.isEmpty(pixelFormat)) {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", IjkMediaPlayer.SDL_FCC_RV32);
                    } else {
                        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "overlay-format", pixelFormat);
                    }
                    ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 1);
                    ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);

                    ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", 0);

                    ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48);
                }
                mediaPlayer = ijkMediaPlayer;
            }
            break;
        }

        if (mSettings.getEnableDetachedSurfaceTextureView()) {
            mediaPlayer = new TextureMediaPlayer(mediaPlayer);
        }

        return mediaPlayer;
    }

    @Override
    public void update(View bindView) {
        int i = 0;
        long time = mAudioController.getTime();
        long length = mAudioController.getLength();
        String url = mAudioController.getCurrentMediaLocation();
        int bindViewId = bindView == null ? 0 : bindView.getId();
        Log.i("update", "time=" + time + ",bindViewId=" + bindViewId + ",length=" + length + ",url=" + url);
    }
}
